<script setup>
import { ref, toRefs } from 'vue'
import { importExcel } from '@/service/excelHttp'
import { ElMessage } from 'element-plus'

defineOptions({
  name: 'ImportExcel'
})
const props = defineProps({
  permitKey: { // 权限关键字
    type: Array,
    default: () => ([])
  },
  downloadName: { // 下载按钮名字
    type: String,
    default: '下载导入模板'
  },
  name: { // 导入按钮名字
    type: String,
    default: '数据'
  },
  size: {
    type: String,
    default: 'default',
    validator: size => ['small', 'default', 'large'].includes(size)
  },
  errMsg: {
    type: String,
    default: '导入失败'
  },
  btnDisabled: {
    type: Boolean,
    default: false
  },
  btnType: String,
  action: String,
  importData: { // 导入的数据
    type: Object,
    default: () => ({})
  }
})
const emit = defineEmits(['update:importData', 'on-success'])
const {name, size, action, btnDisabled} = toRefs(props)
const importRef = ref()
const disabled = ref(false)
const visibleProgressPop = ref(false)
// 进度条
const progressPopRef = ref({})
const loadProgress = ref(0)
const btnRef = ref()

const remove = () => {
  importRef.value.clearFiles()
  disabled.value = false
  emit('update:importData', {})
}
// 上传进度
const importProgress = (event) => {
  disabled.value = true
  visibleProgressPop.value = true // 显示进度条
  loadProgress.value = parseInt(event.percent) // 动态获取文件上传进度
  if (loadProgress.value >= 100) {
    loadProgress.value = 100
  }
}

// 上传前校验
const beforeUpload = (file) => {
  const xlsTypes = ['xls', 'xlsx', 'csv']
  const fileType = file.name.split('.')[1]
  const isXls = xlsTypes.includes(fileType)
  if ( !isXls) {
    ElMessage.error({message: '仅支持.xls/.xlsx/.csv文件'})
    remove()
    return false
  }
  return isXls
}

// 开始上传
const uploadFile = async (file) => {
  const form = new FormData()
  form.append('file', file.raw)
  beforeUpload(file)
  try {
    const res = await importExcel(action.value, form)
    if (res.data.data) { // 通过res.data 是否>0判断是否导入成功
      ElMessage.success({message: `已成功导入${res.data.data}条数据！`})
      emit('on-success')
    } else {
      ElMessage.error(res?.data?.msg || props.errMsg)
    }
  } catch (e) {
    // ElMessage.error({ message: e })
    return e
  } finally {
    remove()
  }
}

</script>
<template>
  <div v-permission="permitKey" class="batch-import-excel">
    <!--  下载导入模板-->
    <ElButton :size="size" icon="Download" @click="emit('on-download')">{{ downloadName }}</ElButton>
    <!-- 批量导入 -->
    <div class="import-excel">
      <ElUpload
          ref="importRef"
          :show-file-list="false"
          accept=".xls,.xlsx,.csv"
          action=""
          :disabled="disabled"
          :on-change="uploadFile"
          :on-progress="(e,file)=>importProgress(e,file)"
          :auto-upload="false">
        <ElButton ref="btnRef" :type="!btnType?'success':null" plain :disabled="btnDisabled" :size="size"
                  :class="btnType">
          导入{{ name }}
        </ElButton>
      </ElUpload>
      <ElPopover
          ref="progressPopRef"
          popper-class="progress-popper"
          placement="top"
          width="160"
          :visible="visibleProgressPop"
          :virtual-ref="btnRef"
          virtual-triggering
          trigger="click">
        <ElProgress :percentage="loadProgress" status="success" style="width: 160px;"/>
      </ElPopover>
    </div>
  </div>
</template>

<style lang="scss">
.batch-import-excel {
  display: inline-block;
  white-space: nowrap;
  padding-left: 12px;

  .import-excel {
    display: inline-block;
    margin: 0 var(--space-primary);

    .el-upload {
    }
  }
}

</style>
